package main

import (
	"flag"
	"gitee.com/zhoulvvv/my_go_gateway/grpc_proxy_router"
	"gitee.com/zhoulvvv/my_go_gateway/http_proxy_router"
	"gitee.com/zhoulvvv/my_go_gateway/router"
	"gitee.com/zhoulvvv/my_go_gateway/services"
	"gitee.com/zhoulvvv/my_go_gateway/tcp_proxy_router"
	"github.com/e421083458/golang_common/lib"
	"os"
	"os/signal"
	"syscall"
)

// endpoint 启动两个终端分别是 dashboard后台管理接口 和 proxy_server代理服务器
// config ./conf/dev/ 对应配置文件夹
// 启动时传递两个参数
// 启动命令 go run main.go -configPath="./conf/dev/" -endpoint=“dashboard”
// 启动命令 go run main.go -configPath="./conf/dev/" -endpoint=“proxy_server”
var (
	endpoint   = flag.String("endpoint", "", "input endpoint dashboard or proxy_server")
	configPath = flag.String("configPath", "", "input configPath file like ./conf/dev/")
)

func main() {
	flag.Parse()
	if *endpoint == "" {
		flag.Usage() // 打印错误提示
		os.Exit(1)
	}
	if *configPath == "" {
		flag.Usage() // 打印错误提示
		os.Exit(1)
	}
	if *endpoint == "dashboard" {
		lib.InitModule(*configPath, []string{"base", "mysql", "redis"})
		defer lib.Destroy()
		router.HttpServerRun() // 启动http服务器
		quit := make(chan os.Signal)
		signal.Notify(quit, syscall.SIGKILL, syscall.SIGQUIT, syscall.SIGINT, syscall.SIGTERM)
		<-quit
		router.HttpServerStop() // 停止http服务器
	} else if *endpoint == "proxy_server" {
		lib.InitModule(*configPath, []string{"base", "mysql", "redis"})
		defer lib.Destroy()
		// 加载服务信息到内存当中
		services.ServiceManagerServiceHandler.LoadOnce()
		// 加载租户信息到内存中
		services.AppManagerHandler.LoadOnce()
		// 启动http服务
		go func() { http_proxy_router.HttpServerRun() }()
		// 启动https服务
		go func() { http_proxy_router.HttpsServerRun() }()
		// 启动TCP服务器
		go func() { tcp_proxy_router.TcpServerRun() }()
		// 启动GRPC服务器
		go func() { grpc_proxy_router.GrpcServerRun() }()
		quit := make(chan os.Signal)
		signal.Notify(quit, syscall.SIGKILL, syscall.SIGQUIT, syscall.SIGINT, syscall.SIGTERM)
		<-quit
		grpc_proxy_router.GrpcServerStop()
		tcp_proxy_router.TcpServerStop()
		http_proxy_router.HttpServerStop()
		http_proxy_router.HttpsServerStop()
	}
}
